package com.globallogic.dailyplanner.webclient.servlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import com.globallogic.dailyplanner.ws.RoleEnum;
import com.globallogic.dailyplanner.ws.UserWS;
import com.globallogic.dailyplanner.ws.UserWebService;
import com.globallogic.dailyplanner.ws.DailyPlanWebService;
import com.globallogic.dailyplanner.ws.DailyPlanWS;


@WebServlet(urlPatterns="index.html")
public class MainServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//TODO make getting web service using CDI
		UserWebService userWebService = new UserWebService();
		UserWS userWS = userWebService.getUserWSImplPort();
		long activeUsers = userWS.getUserCountInfo(true, RoleEnum.USER);
		long inactiveUsers = userWS.getUserCountInfo(false, RoleEnum.USER);
		long admins = userWS.getUserCountInfo(true, RoleEnum.ADMIN);
		
		req.setAttribute("activeUsers", activeUsers);
		req.setAttribute("inactiveUsers", inactiveUsers);
		req.setAttribute("admins", admins);
		
		DailyPlanWebService dailyPlanWebService = new DailyPlanWebService();
		DailyPlanWS dailyPlanWS = dailyPlanWebService.getDailyPlanWSImplPort();
		long totalDailyPlans = dailyPlanWS.getCountOfDailyPlans();

		XMLGregorianCalendar today = null;
		XMLGregorianCalendar lastMonth = null;
		try {
			GregorianCalendar startDate = new GregorianCalendar();
			startDate.add(Calendar.DAY_OF_MONTH, -30);
			GregorianCalendar endDate = new GregorianCalendar();
			
			today = DatatypeFactory.newInstance().newXMLGregorianCalendar(endDate);
			lastMonth = DatatypeFactory.newInstance().newXMLGregorianCalendar(startDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		long lastMonthDailyPlans = dailyPlanWS.getDailyPlansByDate(lastMonth, today);
		
		req.setAttribute("totalDailyPlans", totalDailyPlans);
		req.setAttribute("lastMonthDailyPlans", lastMonthDailyPlans);
		
		req.getRequestDispatcher("index.jsp").forward(req, resp);
	}

}
